package day14;

import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Xiao
 * @date 2021/8/7
 */
public class ThreadPoolDemo04 {
    /**
     * 拒绝策略：
     * 	ThreadPoolExecutor.AbortPolicy：丢弃任务并抛出RejectedExecutionException异常。是默认的策略。
     * 	ThreadPoolExecutor.DiscardPolicy：丢弃任务，但是不抛出异常 这是不推荐的做法。
     * 	ThreadPoolExecutor.DiscardOldestPolicy：抛弃队列中等待最久的任务 然后把当前任务加入队列中。
     * 	ThreadPoolExecutor.CallerRunsPolicy：调用任务的run()方法绕过线程池直接执行。
     */
    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                2,
                3,
                2,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
                //new ThreadPoolExecutor.AbortPolicy());     0,1,2,3,4    RejectedExecutionException
                //new ThreadPoolExecutor.DiscardPolicy());      0,1,2,3,4
                //new ThreadPoolExecutor.DiscardOldestPolicy());      0,1,4,6,7
                //new ThreadPoolExecutor.CallerRunsPolicy());     pool:0,1,2,3,4  main:5,6,7
        for (int i = 0; i < 8; i++) {
            int finalI = i;
            pool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + "在执行" + finalI);
            });
        }
        pool.shutdown();
    }
}
